'''
渲染图片，查看图片生成的结果
'''

import os
import cv2 as cv
from PIL import Image
import xml.etree.ElementTree as Etree
from matplotlib import pyplot as plt
import numpy as np
import json
import math
from scipy.spatial import distance
from collections import OrderedDict
import time
import pandas as pds


def xmlnodeToJson(node):
    if len(node.getchildren()) >0: # 表示存在子节点
        result={node.tag:[]}
        for n in node.getchildren():
            result[node.tag].append(xmlnodeToJson(n))
        return result
    else: # 数据的反复
        return {node.tag:node.text}

def XMLToJson(xmlpath):
    result={}
    conxml=Etree.parse(xmlpath)
    for node in conxml.getroot():
        if not node.tag in result:
            result[node.tag]=[]
        result[node.tag].append(xmlnodeToJson(node))
    return result


def renderImagebyJson():
    # 读取相关的文件，并将数据进行
    csvpath="/media/gis/data/jupyterlabhub/gitcode/hrx/dataset/train_test_vail.csv"
    csvpds=pds.read_csv(csvpath,encoding="utf-8")
    bbox_colors = np.random.randint(0, 255, size=(10, 3))
    # 开始转换数据
    for i in range(0,len(csvpds)):
        anpath=csvpds.iloc[i]["annotation"]
        imgpath=csvpds.iloc[i]['images']
        anjson=XMLToJson(anpath)
        img=cv.imread(imgpath)
        imgname=anjson["filename"][0]["filename"]
        # 解析文件，图像绘图
        for obj in anjson["object"]:
            clr = [int(c) for c in bbox_colors[3]]
            obj=obj["object"]
            for atr in obj:
                if "name" in atr:
                    name=atr["name"]
                if "bndbox" in atr:
                    if  name=="D0":
                        continue
                    bndbox=[int(tt[0]) for tt in [ list(t.values()) for t in atr["bndbox"]]]
                    cv.rectangle(img, (bndbox[0], bndbox[1]), (bndbox[2], bndbox[3]), clr, 2)
        cv.imwrite(os.path.join(".","imageshow",imgname),img)
renderImagebyJson()